﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MySqlSync.Core.Interfaces;
using MySqlSync.Core.Models;
using MySqlSync.DataAccess;
using MySqlSync.Kafka;
using MySqlSync.Redis;
using MySqlSync.SyncService;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("MySQL 同步生产者服务正在启动...");

        // 处理应用程序退出
        var cts = new CancellationTokenSource();
        Console.CancelKeyPress += (sender, e) =>
        {
            e.Cancel = true;
            cts.Cancel();
            Console.WriteLine("正在停止服务，请等待...");
        };

        try
        {
            // 创建主机
            var host = CreateHostBuilder(args).Build();

            // 获取同步服务并启动
            using var scope = host.Services.CreateScope();
            var services = scope.ServiceProvider;

            var syncService = services.GetRequiredService<ISyncProducerService>();
            await syncService.StartAsync(cts.Token);
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("服务已被用户终止");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"服务启动失败: {ex.Message}");
            Console.WriteLine(ex.StackTrace);
        }

        Console.WriteLine("服务已退出");
    }

    static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                config.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true);
                config.AddCommandLine(args);
            })
            .ConfigureServices((hostContext, services) =>
            {
                // 配置
                var syncConfig = hostContext.Configuration.Get<SyncConfig>() ??
                    throw new InvalidOperationException("无法加载同步配置");

                services.AddSingleton(syncConfig);
                services.AddSingleton(syncConfig.Kafka);
                services.AddSingleton(syncConfig.Redis);

                // 服务
                services.AddSingleton<IDbService, DbService>();
                services.AddSingleton<IKafkaProducerService, KafkaProducerService>();
                services.AddSingleton<IRedisService, RedisService>();
                services.AddSingleton<ISyncProducerService, SyncProducerService>();
            });
}